#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "main.h"
#include "elog.h"
#include "console.h"


static SemaphoreHandle_t elog_mux_handle;


ElogErrCode elog_port_init(void)
{
    ElogErrCode result = ELOG_NO_ERR;

    elog_mux_handle = xSemaphoreCreateMutex();
    configASSERT(elog_mux_handle);

    return result;
}

void elog_port_deinit(void)
{
    if (elog_mux_handle)
    {
        vSemaphoreDelete(elog_mux_handle);
    }
}

void elog_port_output(const char *log, size_t size)
{
    console_write((uint8_t *)log, size);
}

void elog_port_output_lock(void)
{
    if (is_user()) {
        xSemaphoreTake(elog_mux_handle, portMAX_DELAY);
    }
}

void elog_port_output_unlock(void)
{
    if (is_user()) {
        xSemaphoreGive(elog_mux_handle);
    }
}

const char *elog_port_get_time(void)
{
    static char fmt_time[64] = "00:00";

    snprintf(fmt_time, sizeof(fmt_time), "%04lu", os_now());

    return fmt_time;
}

const char *elog_port_get_p_info(void)
{
    return pcTaskGetName(NULL);
}

const char *elog_port_get_t_info(void)
{
    return "";
}
